package com.pinda.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.pinda.auth.entity.PdAuthUser;
import com.pinda.auth.entity.PdCoreOrg;
import com.pinda.auth.entity.PdCoreStation;
import com.pinda.auth.search.PdAuthUserSearch;
import com.pinda.auth.view.DriverView;
import com.pinda.auth.view.PasswordView;
import com.pinda.auth.view.PdAuthUserView;
import com.pinda.base.entity.PdTruckDriver;
import com.pinda.authorization.entity.User;
import com.pinda.authorization.entity.pinda.base.BaseController;
import com.pinda.authorization.entity.pinda.base.R;
import com.pinda.commonutils.Key;
import com.pinda.commonutils.Page;
import com.pinda.commonutils.Result;
import com.pinda.commonutils.StatusCode;
import com.pinda.service.IPdAuthUserService;
import com.pinda.work.entity.PdDriverJob;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 黄杰
 * @since 2023-06-13
 */
@RestController
@RequestMapping("/pd_auth_user")
public class PdAuthUserController extends BaseController {
    @Resource
    private IPdAuthUserService iPdAuthUserService;


    @GetMapping("list")
    R<List<User>> list(@RequestParam(name = "ids",required = false) List<Long> ids, @RequestParam(name = "stationId",required = false) Long stationId, @RequestParam(name = "name",required = false) String name, @RequestParam(name = "orgId",required = false) Long orgId){
        System.out.println(ids);
        List<User> pdAuthUsers = this.iPdAuthUserService.listByIdsUser(ids);
        return this.success(pdAuthUsers);
    }
    /**
     * 快递员登录
     *
     * @param msg
     * @return
     */
    @GetMapping("/findUserByAccountOrMobile")
    public Result<PdAuthUser> findUserByAccountOrMobile(String msg) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mobile", msg);
        queryWrapper.or();
        queryWrapper.eq("account",msg);
        PdAuthUser one = iPdAuthUserService.getOne(queryWrapper);
        one.setPassword(Key.rsaDecryptByPrivate(one.getPassword()));
        return Result.<PdAuthUser>builder().data(one).message("查询成功").code(StatusCode.OK).flag(true).build();

    }

    /**
     * 司机登录
     *
     * @return
     */
    @PostMapping("/driverLogin")
    public Result<DriverView> driverLogin(@RequestBody PdAuthUser pdAuthUser) {
        return iPdAuthUserService.driverLogin(pdAuthUser);
    }

    /**
     * TODO 分页条件查询所有用户
     *
     * @param page
     * @return Result<PageInfo < PdAuthUserView>>
     */
    @RequestMapping("findUser")
    public Result<PageInfo<PdAuthUserView>> findUser(@RequestBody Page<PdAuthUserSearch> page) {
        return new Result<PageInfo<PdAuthUserView>>(true, StatusCode.OK, "查询成功", this.iPdAuthUserService.findUserService(page));
    }

    /**
     * TODO 查询所有组织信息
     *
     * @return Result<List < PdCoreOrg>>
     */
    @RequestMapping("findPdCoreOrg")
    public Result<List<PdCoreOrg>> findPdCoreOrg() {
        return new Result<List<PdCoreOrg>>(true, StatusCode.OK, "查询成功", this.iPdAuthUserService.findPdCoreOrgService());
    }

    /**
     * TODO 查询所有岗位信息
     *
     * @return Result<List < PdCoreStation>>
     */
    @RequestMapping("findCoreStation")
    public Result<List<PdCoreStation>> findCoreStation() {
        return new Result<List<PdCoreStation>>(true, StatusCode.OK, "查询成功", this.iPdAuthUserService.findCoreStationService());
    }

    /**
     * TODO 新增用户
     *
     * @param pdAuthUser
     * @return Result<Boolean>
     */
    @RequestMapping("addUser")
    public Result<Boolean> addUser(@RequestBody PdAuthUser pdAuthUser) {
        pdAuthUser.setPassword(Key.rsaEncryptByPublic(pdAuthUser.getPassword()));
        return new Result<Boolean>(true, StatusCode.OK, "新增成功", this.iPdAuthUserService.save(pdAuthUser));
    }

    /**
     * TODO 删除用户
     *
     * @param id
     * @return Result<Boolean>
     */
    @RequestMapping("removeUser/{id}")
    public Result<Boolean> removeUser(@PathVariable("id") String id) {
        return new Result<Boolean>(true, StatusCode.OK, "删除成功", this.iPdAuthUserService.removeById(id));
    }

    /**
     * TODO 编辑用户
     *
     * @param pdAuthUser
     * @return Result<Boolean>
     */
    @RequestMapping("updateUser")
    public Result<Boolean> updateUser(@RequestBody PdAuthUser pdAuthUser) {
        return new Result<Boolean>(true, StatusCode.OK, "编辑成功", this.iPdAuthUserService.updateById(pdAuthUser));
    }


    /**
     * TODO 保存用户头像信息
     *
     * @param myfile
     * @return
     */
    @PostMapping("uploadcontroller")
    public String uploadcontroller(@RequestBody() MultipartFile myfile) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tBDtxb5zU2extkovwUW";
        String accessKeySecret = "oFZi4U5KRMtq1kZy8igFLCXcOD9l2U";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "projectvue";
        //你上传到oss后的名字 会根据日期帮你创建文件夹。
        String objectName = String.valueOf(UUID.randomUUID());
        String hz = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().indexOf(".") + 1);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = myfile.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName + "." + hz, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
        String url = "https://" + bucketName + "." + endpoint + "/" + objectName + "." + hz;
        return url;
    }

    /**
     * 根据编号查询当前登录用户
     */
    @GetMapping("/pd_auth_user/{id}")
    public Result<PdAuthUser> queryLogin(@PathVariable("id") long id) {

        return new Result<>(true, StatusCode.OK, "查询成功", this.iPdAuthUserService.getById(id));
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @PostMapping("/updateuser")
    public Result updateuser(@RequestBody PdAuthUser user) {
        this.iPdAuthUserService.updateById(user);
        return new Result(true, StatusCode.OK, "修改成功", null);
    }

    /**
     * 修改密码
     *
     * @param passwordView
     * @return
     */
    @PostMapping("/updatepassword")
    public Result updatepassword(@RequestBody PasswordView passwordView) {
        int i = this.iPdAuthUserService.CheckPasswordorUpdatePasswordService(passwordView);
        if (i == 1) {
            return new Result(true, StatusCode.OK, "密码更新成功", null);
        } else {
            return new Result(true, StatusCode.ERROR, "旧密码不一致,修改失败", null);
        }
    }
}
